package com.zhenyi.core.wechat.utils;

import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 推送微信模板消息
 * 
 * @author cen
 *
 */
public class TemplateUtils {

	protected final String APP_ID_GZH = PropKit.get("LX_APP_ID_GZH", "");
	protected String APP_ID = PropKit.get("LX_APP_ID", "");
	protected String APP_SECRET = PropKit.get("LX_APP_SECRET", "");
	protected final String ACCESS_TOKEN_KEY = APP_ID + "_AccessToken";
	protected final String URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}";
	protected final String UNIFORM_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=";
	protected final String TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=";
	protected final String TEMPLATE_GZH_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

	private final Cache cache = Redis.use();

	public TemplateUtils(String appId, String appSecret) {
		APP_ID = appId;
		APP_SECRET = appSecret;
	}

	protected String getAccessToken() {
		String token = cache.get(ACCESS_TOKEN_KEY);
		if (StrKit.notBlank(token)) {
			// System.out.println("ret");
			return token;
		}
		String url = StrFormatter.format(URL, APP_ID, APP_SECRET);
		String response = HttpKit.get(url);
		// System.out.println(response);
		JSONObject jsonObject = JSONUtil.parseObj(response);
		String access_token = jsonObject.getStr("access_token");
		int expires_in = jsonObject.getInt("expires_in");
		// int errcode = jsonObject.getInt("errcode");
		// if (errcode != 0) {
		// System.out.println(response);
		// return null;
		// }
		cache.setex(ACCESS_TOKEN_KEY, expires_in, access_token);
		return access_token;
	}

}
